package com.example.hrsystem.ui.workflow;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.TestDataGenerator;
import com.example.hrsystem.workflow.ui.TaskHistoryAdapter;
import com.example.hrsystem.workflow.WorkflowViewModel;

import java.util.ArrayList;

/**
 * 工作流监控Fragment
 * 用于显示流程实例和任务历史记录
 */
public class WorkflowMonitorFragment extends Fragment {

    private WorkflowViewModel workflowViewModel;
    private RecyclerView taskHistoryRecyclerView;
    private TaskHistoryAdapter taskHistoryAdapter;
    private TextView emptyView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_workflow_monitor, container, false);
        
        try {
            // 生成测试数据
            TestDataGenerator.generateTestData(requireContext());
            
            // 初始化ViewModel
            workflowViewModel = new ViewModelProvider(this).get(WorkflowViewModel.class);
            
            // 初始化UI组件
            initUI(view);
            
            // 加载任务历史记录
            loadTaskHistory();
            
            // 加载用户任务数据
            workflowViewModel.loadUserTasks(2); // 加载用户ID为2的任务（与TestDataGenerator中的一致）
        } catch (Exception e) {
            Log.e("WorkflowMonitor", "Error initializing fragment: " + e.getMessage());
            Toast.makeText(requireContext(), "工作流初始化失败", Toast.LENGTH_SHORT).show();
        }
        
        return view;
    }
    
    /**
     * 初始化UI组件
     */
    private void initUI(View view) {
        taskHistoryRecyclerView = view.findViewById(R.id.recycler_view_task_history);
        emptyView = view.findViewById(R.id.text_empty);
        
        // 初始化任务历史记录适配器
        taskHistoryAdapter = new TaskHistoryAdapter();
        taskHistoryRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        taskHistoryRecyclerView.setAdapter(taskHistoryAdapter);
    }
    
    /**
     * 加载任务历史记录
     */
    private void loadTaskHistory() {
        try {
            // 观察任务数据变化
            workflowViewModel.getUserTasks().observe(getViewLifecycleOwner(), tasks -> {
                if (tasks != null && !tasks.isEmpty()) {
                    taskHistoryAdapter.setTaskHistoryList(tasks);
                    taskHistoryRecyclerView.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                } else {
                    taskHistoryRecyclerView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                }
            });
            
            // 观察错误信息
            workflowViewModel.getError().observe(getViewLifecycleOwner(), errorMessage -> {
                if (errorMessage != null) {
                    Log.e("WorkflowMonitor", errorMessage);
                    Toast.makeText(requireContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            Log.e("WorkflowMonitor", "Error loading task history: " + e.getMessage());
            taskHistoryRecyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        }
    }
}